<?php
/**
 * @Author: liuhongbin
 * @Email: 514660094@qq.com
 * @Date: 2019-02-12 16:15:10
 * @Description:
 * @LastEditors: liuhongbin
 * @LastEditTime: xxx
 */

namespace addons\cloud_market\controller\api\developer;

use addons\cloud_market\controller\api\CloudMarketApiController;
use addons\cloud_market\model\CloudMarketAddon;
use addons\cloud_market\model\CloudMarketOrder;
use addons\cloud_market\model\CloudMarketSiteAddon;

class Index extends CloudMarketApiController
{
    protected $notApiLogin = [];
    protected $notApiCheck = [];

    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $user = $this->getUser();
        if (!$user['developer']) {
            showMessage("您没有权限",'error','','-1');
        }
        $this->dev_id = $user['developer']['id'];
        $this->user_id = $user['id'];
    }

    public function dashboard()
    {
        $aids = (new CloudMarketAddon())->where(['user_id' => $this->user_id, 'dev_id' => $this->dev_id])->column('id');
        // 我想获取购买产品的用户数量，也就是上面的模型通过user_id去重后得到的总数
        $user_count = (new CloudMarketOrder())
            ->whereIn('aid', $aids)
            ->distinct('user_id')
            ->count('user_id');

// 获取总收益
        $total_earnings = (new CloudMarketOrder())
            ->whereIn('aid', $aids)
            ->where('status', 1)
            ->sum('total_fee');

        $site_count = (new CloudMarketSiteAddon())->whereIn('addon_id', $aids)->count();
        $data = [
            'addon_count'    => count($aids),
            'user_count'     => $user_count,
            'total_earnings' => round($total_earnings / 100, 2),
            'site_count'     => $site_count
        ];

        return $this->success('', $data);
    }
}
